package com.example.helloworld

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.android.material.snackbar.Snackbar

class HistoryActivity : AppCompatActivity() {
    private lateinit var adapter: TimerRecordAdapter
    private val records = mutableListOf<TimerRecord>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_history)

        // 设置返回按钮处理
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        })

        // 设置操作栏的返回箭头
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        // 设置标题
        title = "历史记录"

        val recyclerView = findViewById<RecyclerView>(R.id.recordsRecyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)

        adapter = TimerRecordAdapter(
            records,
            onDeleteClick = { record -> showDeleteDialog(record) }
        )
        recyclerView.adapter = adapter

        loadRecords()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.history_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_delete_all -> {
                showDeleteAllConfirmDialog()
                true
            }
            android.R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showDeleteAllConfirmDialog() {
        AlertDialog.Builder(this)
            .setTitle("删除全部记录")
            .setMessage("确定要删除所有记录吗？此操作不可恢复。")
            .setPositiveButton("删除") { _, _ ->
                deleteAllRecords()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deleteAllRecords() {
        records.clear()
        saveRecords()
        adapter.notifyDataSetChanged()
        
        // 显示删除成功提示
        Snackbar.make(
            findViewById(R.id.recordsRecyclerView),
            "已删除所有记录",
            Snackbar.LENGTH_SHORT
        ).show()
    }

    private fun loadRecords() {
        val prefs = getSharedPreferences("timer_records", MODE_PRIVATE)
        val json = prefs.getString("records", "[]")
        val type = object : TypeToken<List<TimerRecord>>() {}.type
        records.clear()
        records.addAll(Gson().fromJson<List<TimerRecord>>(json, type))
        
        // 按保存时间倒序排序（最新的记录在前面）
        records.sortByDescending { it.savedTime }
        
        adapter.notifyDataSetChanged()
    }

    private fun saveRecords() {
        val json = Gson().toJson(records)
        getSharedPreferences("timer_records", MODE_PRIVATE)
            .edit()
            .putString("records", json)
            .apply()
    }

    private fun showDeleteDialog(record: TimerRecord) {
        AlertDialog.Builder(this)
            .setTitle("删除记录")
            .setMessage("确定要删除这条记录吗？")
            .setPositiveButton("确定") { _, _ ->
                records.remove(record)
                saveRecords()
                adapter.notifyDataSetChanged()
            }
            .setNegativeButton("取消", null)
            .show()
    }
} 